import React, { useState } from 'react';
import { Space, Tag, Button, message, Modal, Tooltip, Badge, App as AntdApp, Checkbox, Spin } from 'antd';
import { UserOutlined, EditOutlined, DeleteOutlined, EyeOutlined, PlusOutlined, ExclamationCircleOutlined, TeamOutlined } from '@ant-design/icons';
import AdvancedTable from '@/components/common/AdvancedTable/AdvancedTable';
import { useTable } from '@/components/common/AdvancedTable/useTable';
import { LoadingButton } from '@/components/common/LoadingButton';
import type { User, UserPageParams, UserCreateParams, UserUpdateParams, Role } from '@/api/system';
import { getUserPage, createUser, updateUser, deleteUser, getRoleList, getUserRoles, assignUserRoles } from '@/api/system';
import { DynamicForm } from '@/components/common/DynamicForm';
import { createUserFormConfig } from './components/UserFormConfig';

const Users: React.FC = () => {
  const { modal } = AntdApp.useApp();
  const [userFormVisible, setUserFormVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [viewingUser, setViewingUser] = useState<User | null>(null);
  const [stickyHeaderEnabled, setStickyHeaderEnabled] = useState(true);
  const [roleAssignVisible, setRoleAssignVisible] = useState(false);
  const [assigningUser, setAssigningUser] = useState<User | null>(null);
  const [allRoles, setAllRoles] = useState<Role[]>([]);
  const [userRoles, setUserRoles] = useState<Role[]>([]);
  const [loadingRoles, setLoadingRoles] = useState(false);
  const [submittingRoles, setSubmittingRoles] = useState(false);

  // 表格配置
  const table = useTable<User>({
    queryKey: 'system-users',
    fetchData: async (params) => {
      const response = await getUserPage({
        pageNo: params.page,
        pageSize: params.pageSize,
        username: params.search?.username,
        name: params.search?.name,
        mobile: params.search?.mobile,
      });

      // API 响应处理

      // 确保response存在并且有数据
      if (!response) {
        return {
          data: [],
          total: 0,
          page: params.page,
          pageSize: params.pageSize,
        };
      }

      // 根据新的API响应结构处理数据，response现在就是data字段的内容
      return {
        data: Array.isArray(response.list) ? response.list : [],
        total: parseInt(response.total) || 0,
        page: params.page,
        pageSize: params.pageSize,
      };
    },
    defaultPageSize: 10,
    searchFields: [
      {
        key: 'username',
        label: '用户名',
        type: 'input',
        placeholder: '请输入用户名',
      },
      {
        key: 'name',
        label: '姓名',
        type: 'input',
        placeholder: '请输入姓名',
      },
      {
        key: 'mobile',
        label: '手机号',
        type: 'input',
        placeholder: '请输入手机号',
      },
    ],
    onSuccess: (data) => {
      // 用户数据获取成功
    },
    onError: (error) => {
      // 用户数据获取失败
      message.error('用户数据加载失败');
    },
  });

  // 表格列定义
  const columns = [
    {
      key: 'id',
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      sorter: true,
      hidden: true, // 隐藏ID列
    },
    {
      key: 'username',
      title: '用户名',
      dataIndex: 'username',
      width: 120,
      sorter: true,
      render: (text: string) => (
        <Space>
          <UserOutlined />
          {text}
        </Space>
      ),
    },
    {
      key: 'name',
      title: '姓名',
      dataIndex: 'name',
      width: 120,
      sorter: true,
      render: (text: string) => text || '-',
    },
    {
      key: 'mobile',
      title: '手机号',
      dataIndex: 'mobile',
      width: 140,
      ellipsis: true,
      render: (mobile: string) => mobile || '-',
    },
    // 删除邮箱列，因为数据显示为"demoData"，不是真实的邮箱
    // 删除状态列，因为API返回的数据中没有status字段
    // 删除部门ID列，因为API返回的数据中没有deptId字段
    // 删除登录IP列，因为API返回的数据中没有loginIp字段
    // 删除最后登录时间列，因为API返回的数据中没有loginDate字段
    {
      key: 'createTime',
      title: '创建时间',
      dataIndex: 'createTime',
      width: 180,
      sorter: true,
      render: (text: string) => text ? new Date(text).toLocaleString() : '-',
    },
    // 删除备注列，因为API返回的数据中没有remark字段
    {
      key: 'actions',
      title: '操作',
      dataIndex: 'actions',
      width: 200,
      fixed: 'right',
      render: (_text: any, record: User) => (
        <Space size="small">
          <LoadingButton
            type="link"
            size="small"
            icon={<EyeOutlined />}
            tooltip="查看"
            onClick={() => handleViewUser(record)}
          />
          <LoadingButton
            type="link"
            size="small"
            icon={<EditOutlined />}
            tooltip="编辑"
            onClick={() => handleEditUser(record)}
          />
          <LoadingButton
            type="link"
            size="small"
            icon={<TeamOutlined />}
            tooltip="分配角色"
            loading={assigningUser?.id === record.id && (loadingRoles || submittingRoles)}
            onClick={() => handleAssignRole(record)}
            debounceMs={1000}
          />
          <LoadingButton
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            tooltip="删除"
            onClick={() => handleDeleteUser(record)}
          />
        </Space>
      ),
    },
  ];

  // 批量操作
  const batchActions = [
    {
      key: 'batchDelete',
      label: '批量删除',
      icon: <DeleteOutlined />,
      danger: true,
      onClick: (selectedRows: User[]) => {
        modal.confirm({
          title: '确认批量删除',
          content: `确定要删除选中的 ${selectedRows.length} 个用户吗？`,
          icon: <ExclamationCircleOutlined />,
          onOk: async () => {
            try {
              await deleteUser(selectedRows.map(row => row.id));
              message.success(`成功删除 ${selectedRows.length} 个用户`);
              table.refresh();
            } catch (error) {
              message.error('批量删除失败');
            }
          },
        });
      },
    },
    {
      key: 'batchEnable',
      label: '批量启用',
      onClick: (selectedRows: User[]) => {
        message.info(`批量启用 ${selectedRows.length} 个用户`);
      },
    },
    {
      key: 'batchDisable',
      label: '批量禁用',
      onClick: (selectedRows: User[]) => {
        message.info(`批量禁用 ${selectedRows.length} 个用户`);
      },
    },
  ];

  // 查看用户
  const handleViewUser = (user: User) => {
    setViewingUser(user);
  };

  // 编辑用户
  const handleEditUser = (user: User) => {
    setEditingUser(user);
    setUserFormVisible(true);
  };

  // 删除用户
  const handleDeleteUser = (user: User) => {
    modal.confirm({
      title: '确认删除',
      content: `确定要删除用户 "${user.username}" 吗？`,
      icon: <ExclamationCircleOutlined />,
      onOk: async () => {
        try {
          await deleteUser(user.id);
          message.success('删除成功');
          table.refresh();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 创建用户
  const handleCreateUser = () => {
    setEditingUser(null);
    setUserFormVisible(true);
  };

  // 处理表单提交
  const handleFormSubmit = async (values: UserCreateParams | UserUpdateParams) => {
    try {
      if (editingUser) {
        // 更新用户
        await updateUser(values as UserUpdateParams);
        message.success('用户更新成功');
      } else {
        // 创建用户
        await createUser(values as UserCreateParams);
        message.success('用户创建成功');
      }
      setUserFormVisible(false);
      table.refresh();
    } catch (error) {
      message.error(editingUser ? '用户更新失败' : '用户创建失败');
    }
  };

  // 分配角色
  const handleAssignRole = async (user: User) => {
    // 如果正在加载或提交，不允许重复点击
    if (loadingRoles || submittingRoles) {
      return;
    }

    setAssigningUser(user);
    setRoleAssignVisible(true);
    setLoadingRoles(true);

    try {
      // 并行获取所有角色和用户当前角色
      const [allRolesResponse, userRolesResponse] = await Promise.all([
        getRoleList(),
        getUserRoles(user.id)
      ]);

      setAllRoles(allRolesResponse || []);
      setUserRoles(userRolesResponse || []);
    } catch (error) {
      message.error('获取角色信息失败');
      setRoleAssignVisible(false);
    } finally {
      setLoadingRoles(false);
    }
  };

  // 处理角色分配提交
  const handleRoleAssignSubmit = async () => {
    if (!assigningUser || submittingRoles) return;

    setSubmittingRoles(true);

    try {
      const selectedRoleIds = userRoles.map(role => role.id);
      await assignUserRoles(assigningUser.id, selectedRoleIds);
      message.success('角色分配成功');
      setRoleAssignVisible(false);
      setUserRoles([]);
      setAllRoles([]);
    } catch (error) {
      message.error('角色分配失败');
    } finally {
      setSubmittingRoles(false);
    }
  };

  // 处理角色选择变化
  const handleRoleChange = (roleId: string | number, checked: boolean) => {
    if (checked) {
      // 添加角色
      const roleToAdd = allRoles.find(role => role.id === roleId);
      if (roleToAdd) {
        setUserRoles(prev => [...prev, roleToAdd]);
      }
    } else {
      // 移除角色
      setUserRoles(prev => prev.filter(role => role.id !== roleId));
    }
  };

  // 生成动态表单配置
  const userFormConfig = createUserFormConfig(!!editingUser);

  return (
    <div style={{ padding: 24, height: 'calc(100vh - 180px)', display: 'flex', flexDirection: 'column' }}>
      <AdvancedTable<User>
        columns={columns}
        dataSource={table.data}
        loading={table.loading}
        pagination={table.pagination}
        searchFields={table.searchFields}
        onSearch={table.handleSearch}
        refresh={table.refresh}
        batchActions={batchActions}
        stickySettings={{
          enabled: true,
          header: stickyHeaderEnabled,
          offsetTop: 64,
          onHeaderChange: (enabled) => {
            setStickyHeaderEnabled(enabled);
          },
        }}
        scroll={{ x: 1400 }}
        extra={
          <LoadingButton
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleCreateUser}
            tooltip="新增用户"
          >
            新增用户
          </LoadingButton>
        }
        onChange={table.handleTableChange}
        rowSelection={{
          type: 'checkbox',
          onChange: (selectedRowKeys, selectedRows) => {
            // 行选择变化处理
          },
        }}
        rowClassName={(_record, index) => {
          return index % 2 === 0 ? 'even-row' : 'odd-row';
        }}
        onRow={(record) => {
          return {
            onClick: (_event) => {
              // 行点击处理
            },
            onDoubleClick: (_event) => {
              // 行双击处理
            },
          };
        }}
      />

      {/* 用户表单对话框 */}
      <DynamicForm
        config={userFormConfig}
        values={editingUser || undefined}
        visible={userFormVisible}
        onSubmit={handleFormSubmit}
        onCancel={() => setUserFormVisible(false)}
        width={800}
      />

      {/* 角色分配对话框 */}
      <Modal
        title={`分配角色 - ${assigningUser?.username || ''}`}
        open={roleAssignVisible}
        onOk={handleRoleAssignSubmit}
        onCancel={() => {
          setRoleAssignVisible(false);
          setUserRoles([]);
          setAllRoles([]);
        }}
        width={600}
        confirmLoading={submittingRoles}
      >
        <Spin spinning={loadingRoles}>
          <div style={{ padding: '20px 0' }}>
            <div style={{ marginBottom: 16 }}>
              <strong>选择角色：</strong>
            </div>
            <div style={{ maxHeight: 400, overflowY: 'auto' }}>
              {allRoles.map(role => (
                <div key={role.id} style={{ marginBottom: 8 }}>
                  <Checkbox
                    checked={userRoles.some(userRole => userRole.id === role.id)}
                    onChange={(e) => handleRoleChange(role.id, e.target.checked)}
                  >
                    <Space>
                      <UserOutlined />
                      <span>{role.name}</span>
                      <Tag color="blue">{role.code}</Tag>
                    </Space>
                  </Checkbox>
                </div>
              ))}
            </div>
            {allRoles.length === 0 && !loadingRoles && (
              <div style={{ textAlign: 'center', color: '#999', padding: '20px' }}>
                暂无可用角色
              </div>
            )}
          </div>
        </Spin>
      </Modal>

      {/* 用户详情对话框 */}
      <Modal
        title="用户详情"
        open={!!viewingUser}
        onCancel={() => setViewingUser(null)}
        footer={null}
        width={600}
      >
        {viewingUser && (
          <div style={{ padding: '20px 0' }}>
            <Space direction="vertical" style={{ width: '100%' }} size="middle">
              <div>
                <strong>用户名：</strong>
                <span style={{ marginLeft: 8 }}>{viewingUser.username}</span>
              </div>
              <div>
                <strong>姓名：</strong>
                <span style={{ marginLeft: 8 }}>{viewingUser.name}</span>
              </div>
              <div>
                <strong>手机号：</strong>
                <span style={{ marginLeft: 8 }}>{viewingUser.mobile}</span>
              </div>
              <div>
                <strong>邮箱：</strong>
                <span style={{ marginLeft: 8 }}>{viewingUser.email || '-'}</span>
              </div>
              <div>
                <strong>创建时间：</strong>
                <span style={{ marginLeft: 8 }}>
                  {viewingUser.createTime ? new Date(viewingUser.createTime).toLocaleString() : '-'}
                </span>
              </div>
            </Space>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default Users;